package org.zsk.cs.algorithnm.loadbalance.sendorder.impl;

import org.zsk.cs.algorithnm.entity.EmployTask;
import org.zsk.cs.algorithnm.loadbalance.sendorder.LoadBalance;
import org.zsk.cs.algorithnm.loadbalance.sendorder.SendOrderUtil;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 负载均衡-轮询派单
 * @author zsk
 * 2021/3/11 下午3:56
 */
public class RoundRobinLoadBalancer implements LoadBalance<EmployTask> {

    private static AtomicInteger idx = new AtomicInteger(0);

    @Override
    public EmployTask pickOne() {
        List<EmployTask> employTasks = SendOrderUtil.getEmployTasksInList();
        int index = getNextNonNegative();
        for (int i = 0; i < employTasks.size(); i++) {
            //获取服务
            EmployTask employTask = employTasks.get((i + index) % employTasks.size());
            //判断服务是否可用
            if (employTask.getStatus().equals("00")) {
                return employTask;
            }
        }
        return null;
    }

    private int getNextNonNegative() {
        return getNonNegative(idx.incrementAndGet());
    }

    /**
     * 通过二进制位操作将originValue转化为非负数:
     * 0和正数返回本身
     * 负数通过二进制首位取反转化为正数或0（Integer.MIN_VALUE将转换为0）
     * return non-negative int value of originValue
     *
     * @param originValue
     * @return positive int
     */
    public int getNonNegative(int originValue) {
        return 0x7fffffff & originValue;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            System.out.println(new RoundRobinLoadBalancer().pickOne().toString());
        }
    }
}

